package com.cash.app.utils

import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.cash.app.constant.AppConstant
import com.cash.app.manager.GlobalTaskManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object GPAIdUtils {

    private const val TAG = "GAIdUtils"

    fun init(context: Context) {
        GlobalTaskManager.launchTask(TAG) {
            fetchSaveGAdId(context)
        }
    }

    @SuppressLint("HardwareIds")
    private fun fetchSaveAndroidId(context: Context) {
        try {
            // val uuId = UUID.randomUUID().toString()
            val androidId = Settings.Secure.getString(
                context.contentResolver, Settings.Secure.ANDROID_ID
            )
            SpUtils.put(AppConstant.K_GA_ID, androidId)
            TLog.d("fetchSaveAndroidId success androidId=$androidId", TAG)
        } catch (e: Exception) {
            TLog.d("fetchSaveAndroidId error", TAG, e)
        }
    }

    private suspend fun fetchSaveGAdId(context: Context) = withContext(Dispatchers.IO) {
        // Calling this from your main thread can lead to deadlock
        //	at com.google.android.gms.common.internal.Preconditions.checkNotMainThread
        try {
            val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)

            if (adInfo.isLimitAdTrackingEnabled) {
                // return: 00000000-0000-0000-0000-000000000000
                TLog.d("fetchSaveGAdId isLimitAdTrackingEnabled", TAG)
                fetchSaveAndroidId(context)
            } else {
                adInfo.id?.let { id ->
                    SpUtils.put(AppConstant.K_GA_ID, id)
                    TLog.d("fetchSaveGAdId into sp", TAG)
                }
            }

            //return@withContext adInfo.id
        } catch (e: Exception) {
            //e.printStackTrace()
            // GooglePlayServicesNotAvailableException
            // IOException
            // GooglePlayServicesRepairableException
            // IllegalStateException
            // AdvertisingIdClient cannot reconnect.GooglePlayServicesNotAvailableException
            TLog.d("gaid get error", TAG, e)
            fetchSaveAndroidId(context)
            //return@withContext null
        }
    }
}